package com.sqfw.project.utils.smgp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.UnsupportedEncodingException;

//@Component
public class SMGPSmsTool {

	//private static int count = 0;

	@Autowired
	private SMGPSession session;

	@PostConstruct
	public void init(){
		// 在构造方法SMGPSmsTool执行之后，开始建立smgp连接
		Thread thread = new Thread(session);
		thread.setName("SMGPSession");
		//thread.start();
	}

	public void sendMsg(String receivePhone,String content){
		// if(count == 0) init();
		SMGPSubmitMessage submit = new SMGPSubmitMessage();
		submit.setSrcTermId("10692202277046009");
		submit.setDestTermIdArray(new String[] { receivePhone });
		submit.setMsgFmt((byte) 8);
		content =  "【三网平台】" + content;
		byte[] bContent = null;
		try {
			bContent = content.getBytes("iso-10646-ucs-2");
		} catch (UnsupportedEncodingException e) {}

		if (bContent.length <= 140) {
			submit.setBMsgContent(bContent);

			submit.setMsgFmt((byte) 8);
//				submit.setMsgFmt((byte) 0);
			submit.setNeedReport((byte) 1);
			submit.setServiceId("");
			submit.setSequenceNumber(RandomGenerator.getAbsInt());
			submit.setAtTime("");
			//opt
			submit.setTpPid((byte) 0);
			submit.setTpUdhi((byte) 0);

			session.send(submit);
		} else {
			int num = bContent.length / 134;
			int endNum = bContent.length % 134;
			if ( endNum != 0) {
				num = num + 1;
			}

			byte[] head = new byte[6];
			head[0] = 5;
			head[1] = 0;
			head[2] = 3;
			head[3] = (byte) RandomGenerator.getByte();
			head[4] = (byte) num;

			for (int i = 0; i < num; i++) {
				byte[] b = null;
				if(i==num-1 && endNum != 0){
					b = new byte[(endNum+6)];
				}else{
					b = new byte[140];
				}

				head[5] = (byte) (i + 1);
				System.arraycopy(head, 0, b, 0, head.length);

				int len = Math.min(134, bContent.length - 134 * i);

				System.arraycopy(bContent, i * 134, b, head.length, len);

				submit.setBMsgContent(b);
				submit.setMsgFmt((byte) 8);
				submit.setNeedReport((byte) 1);
				submit.setServiceId("");
				submit.setSequenceNumber(RandomGenerator.getAbsInt());
				submit.setAtTime("");
				//opt
				submit.setTpPid((byte) 0);
				submit.setTpUdhi((byte) 1);

				session.send(submit);
			}
		}
	}


}
